using System.Collections;
using System.Collections.Generic;
using AddressablesTool;
using Core.Scene;
using Cysharp.Threading.Tasks;
using Managers;
using UnityEngine;
using UnityEngine.SceneManagement;
using Utils.Singleton;

namespace Helpers
{
    public class SceneHelper : CommonSingleton<SceneHelper>
    {
        protected override MonoBehaviour BindMono => GameManager.Singleton;

        public SceneInfo CurrentSceneInfo { private set; get; }
        private SceneLoader _scenes;

        public IEnumerator LoadScenesCoroutine(SceneInfo sceneInfo)
        {
            if (IsSameScene(sceneInfo))
                yield break;
            if (_scenes == null)
                _scenes = AddressablesManager.Singleton.SceneLoader;

            if (!string.IsNullOrEmpty(sceneInfo.MainScene))
                yield return _scenes.LoadSceneAsync(sceneInfo.MainScene).ToCoroutine();
            if (!string.IsNullOrEmpty(sceneInfo.SubScene))
                yield return _scenes.LoadSceneAsync(sceneInfo.SubScene, LoadSceneMode.Additive).ToCoroutine();
            CurrentSceneInfo = sceneInfo;
        }

        public bool IsSameScene(SceneInfo sceneInfo)
        {
            if (CurrentSceneInfo == null)
                return false;
            return _scenes.IsSceneActuallyLoaded(sceneInfo.MainScene) && _scenes.IsSceneActuallyLoaded(sceneInfo.SubScene);
        }
    }

    public static class SceneHelperExtensions
    {
        public static IEnumerator LoadScenesCoroutine(this SceneLoader loader, SceneInfo sceneInfo)
        {
            return SceneHelper.Singleton.LoadScenesCoroutine(sceneInfo);
        }

        public static bool IsSameScene(this SceneLoader loader, SceneInfo sceneInfo)
        {
            return SceneHelper.Singleton.IsSameScene(sceneInfo);
        }

        public static SceneInfo GetSceneInfo(this SceneLoader loader)
        {
            return SceneHelper.Singleton.CurrentSceneInfo;
        }
    }
}